import 'dart:async';
import 'dart:typed_data';

import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:flutter/material.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:ts_app_dart/utils/index.dart';

bool locateChangeVal = false;

class LocationPage extends StatefulWidget {
  const LocationPage({Key key}) : super(key: key);

  @override
  _LocationPageState createState() => _LocationPageState();
}

class _LocationPageState extends State<LocationPage> {
  String applicationId;
  LatLng latLng;
  Map<String, Marker> _initMarkerMap = {};
  AMapFlutterLocation _locationPlugin = new AMapFlutterLocation();

  // https://lbs.amap.com/api/flutter/guide/map-flutter-plug-in/interaction-with-map
  AMapController _controller;

  void _onMapCreated(AMapController controller) {
    setState(() {
      _controller = controller;
    });
  }

  @override
  void initState() {
    super.initState();
    print('xxxxxx setApiKey xxxxxx');
    requestLocationPermission();

    AMapFlutterLocation.updatePrivacyAgree(true);
    AMapFlutterLocation.updatePrivacyShow(true, true);

    AMapFlutterLocation.setApiKey(
      "c77d699de5b39335ab285429f9fd14a5",
      "cce970a5939d95a9db9df3dee88f969a",
    );

    _locationPlugin.onLocationChanged().listen((Map<String, Object> result) {
      print('---- onLocationChanged ----');
      print(result);
      var longitude = result['longitude'];
      var latitude = result['latitude'];
      if (longitude is String) {
        latitude = double.parse(latitude);
        longitude = double.parse(longitude);
      }
      print('longitude > 0 => $longitude');

      var _locationText = 'Address Site:' +
          (result['city'] ?? '') +
          (result['district'] ?? '') +
          (result['street'] ?? 'unkown');

      CameraUpdate cameraUpdate = CameraUpdate.newCameraPosition(
        CameraPosition(
          target: (longitude as double) > 0
              ? LatLng(latitude, longitude)
              : LatLng(30.568738, 104.063117),
          zoom: 16,
          tilt: 0,
          // tilt: 30,
          bearing: 0,
        ),
      );
      if (locateChangeVal == true) {
        locateChangeVal = false;
        _controller.moveCamera(cameraUpdate);
        Fluttertoast.showToast(msg: _locationText);
      }
    });
    var locationOption = AMapLocationOption();
    // 是否单次定位
    locationOption.onceLocation = false;
    // 是否需要返回逆地理信息
    locationOption.needAddress = true;
    // 逆地理信息的语言类型
    locationOption.geoLanguage = GeoLanguage.ZH;
    _locationPlugin.setLocationOption(locationOption);

    // _addMarker(LatLng(30.568738, 104.063117));
  }

  @override
  void dispose() {
    super.dispose();
    _locationPlugin?.stopLocation();
  }

  // ignore: unused_element
  Future<void> _addMarker(LatLng mLatLng) async {
    final _markerPosition = mLatLng;
    Widget widget = Container(
      height: 200.0,
      width: 500.0,
      color: Colors.deepOrangeAccent,
      child: Column(
        children: [
          Expanded(
            flex: 1,
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(
                  Radius.circular(16.0),
                ),
              ),
              // width: double.infinity,
              child: Padding(
                padding: EdgeInsets.all(0.0),
                child: Column(
                  children: [
                    // 必须用Directionality包裹，否则会引起崩溃
                    Directionality(
                      textDirection: TextDirection.ltr,
                      child: Text(
                        'This is a example',
                        style: TextStyle(
                          fontSize: 40,
                          color: Colors.black,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          // Directionality(
          //   textDirection: null,
          //   child: Padding(
          //     padding: const EdgeInsets.only(right: 12.0),
          //     child: Transform.rotate(
          //       angle: 180,
          //       child: Image.asset('images/up_arrow.png',
          //           width: 160.0, height: 80.0),
          //     ),
          //   ),
          // ),
        ],
      ),
    );
    Uint8List widgets = await AmpMaker.convertWidgetToImage(widget);
    final Marker marker = Marker(
      position: _markerPosition,
      icon: BitmapDescriptor.fromBytes(widgets),
    );
    // 调用setState触发AMapWidget的更新，从而完成marker的添加
    setState(() {
      _initMarkerMap[marker.id] = marker;
    });
  }

  AMapWidget aMapWidgetCreate() {
    return AMapWidget(
      privacyStatement: AMapPrivacyStatement(
          hasShow: true, hasAgree: true, hasContains: true),
      apiKey: AMapApiKey(
          iosKey: 'cce970a5939d95a9db9df3dee88f969a',
          androidKey: 'c77d699de5b39335ab285429f9fd14a5'),
      onMapCreated: _onMapCreated,
      rotateGesturesEnabled: true,
      scrollGesturesEnabled: true,
      tiltGesturesEnabled: true,
      zoomGesturesEnabled: true,
      initialCameraPosition: CameraPosition(
        zoom: 12,
        target: latLng ?? LatLng(30.568738, 104.063117),
      ),
      markers: Set<Marker>.of(_initMarkerMap.values),
      // 限制显示区域
      // limitBounds: LatLngBounds(
      //   southwest: LatLng(39.83309, 116.290176),
      //   northeast: LatLng(39.99951, 116.501663),
      // ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('LocationPage'),
      ),
      body: SafeArea(
        child: aMapWidgetCreate(),
      ),
      floatingActionButton: Container(
        height: 150.0,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(8.0),
          ),
          color: Colors.cyan[100],
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            IconButton(
              iconSize: 30.0,
              onPressed: () {
                locateChangeVal = true;
                _locationPlugin.startLocation();
              },
              icon: Icon(Icons.location_on),
            ),
            IconButton(
              iconSize: 30.0,
              onPressed: () {
                _controller.moveCamera(CameraUpdate.zoomIn());
              },
              icon: Icon(Icons.zoom_in),
            ),
            IconButton(
              iconSize: 30.0,
              onPressed: () {
                _controller.moveCamera(CameraUpdate.zoomOut());
              },
              icon: Icon(Icons.zoom_out),
            ),
          ],
        ),
      ),
    );
  }

  Future<bool> requestLocationPermission() async {
    // 获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      // 已经授权
      return true;
    } else {
      // 未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }
}
